//
//  WKNetworkTools.m
//  WeKeTang
//
//  Created by ichina on 2017/8/23.
//  Copyright © 2017年 Dezhi Tiancheng Education Technology (Beijing) Co. Ltd. All rights reserved.
//

#import "WKNetworkTools.h"
#import "WKLoginViewController.h"
#import "NSString+MKNetworkKitAdditions.h"
#import "UIDevice+KZExtension.h"
#import "WKAlerView.h"
#import "WKUniversal.h"
#import "NSString+Addition.h"
#import "WKLoginHandel.h"
static NSString * const kProtocolLocalizedDescription = @"网络连接错误";
static NSString * const secret =@"1248909376";

@interface WKNetworkTools ()

@property (strong, nonatomic) NSString *decodeKey;
@property (strong, nonatomic) NSString *deviceId;
@property (strong, nonatomic) NSString *appVersion;
@property (strong, nonatomic) MBProgressHUD *HUD;

@end

@implementation WKNetworkTools

+ (WKNetworkTools*)shareManger{
    
    static WKNetworkTools *manger;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken,^{
        manger = [[WKNetworkTools alloc] init];
    });
    
    return manger;
}
- (instancetype)init{
    
    self = [super init];
    
    if(self){
//        self.deviceId = mydeviceUniqueIdentifier();
        self.appVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
        self.httpMethod = @"GET";
        self.needLogin = YES;
    }
    return self;
}
- (void)setRequestPost{
    
    self.httpMethod = @"POST";
}
//不带提示框的
- (NSURLSessionDataTask*)RunNoneRequest:(NSMutableDictionary *)dict
                               path:(NSString *)path
                               tip :(NSString*)tip
                  completionHandler:(ResponseBlock)completionBlock
                       errorHandler:(AFNErrorBlock)errorBlock
                      finishHandler:(FinishBlock)finishBlock{
    
    return [self RunNoneRequest:dict path:path tip:tip useSSL:NO completionHandler:completionBlock errorHandler:errorBlock finishHandler:finishBlock];
    
}
- (NSURLSessionDataTask* )RunNoneRequest:(NSMutableDictionary *)  dict
                                path:(NSString *)path
                                tip :(NSString*)tip
                              useSSL:(BOOL)useSSL
                   completionHandler:(ResponseBlock)completionBlock
                        errorHandler:(AFNErrorBlock)errorBlock
                       finishHandler:(FinishBlock)finishBlock{
    
    NSMutableDictionary *paramDict = [self obtainParametersDictionaryWithDic:dict];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //headers
    [manager.requestSerializer setValue:@"gzip, deflate, sdch" forHTTPHeaderField:@"Accept-Encoding"];
    [manager.requestSerializer setValue:@"zh,CN" forHTTPHeaderField:@"Accept-Language"];
    [manager.requestSerializer setValue:@"text/json" forHTTPHeaderField:@"Content-Type"];
    
    AFJSONResponseSerializer *serializer = [AFJSONResponseSerializer serializer];
    serializer.acceptableContentTypes = [NSSet setWithObjects:@"text/json",@"text/html",@"application/json", nil];
    manager.responseSerializer = serializer;
    
    NSURLSessionDataTask *task = nil;
    __weak typeof(self) weakSelf = self;
    task = [manager POST:path parameters:paramDict constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [weakSelf analysisDataWithObject:responseObject path:task.currentRequest.description completionHandler:completionBlock finishHandler:finishBlock];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

        if (error.code==NSURLErrorCancelled) {
            error = [[NSError alloc] initWithDomain:@"" code:999 userInfo:nil];
        }else{
            error = [[NSError alloc] initWithDomain:kProtocolLocalizedDescription code:201 userInfo:nil];
        }
        if (errorBlock) {
            errorBlock(error);
        }
    }];
    return task;
}
//带提示框的
- (NSURLSessionDataTask*)RunRequest:(NSMutableDictionary *)dict
                               path:(NSString *)path
                               tip :(NSString*)tip
                  completionHandler:(ResponseBlock)completionBlock
                       errorHandler:(AFNErrorBlock)errorBlock
                      finishHandler:(FinishBlock)finishBlock{
    
    return [self RunRequest:dict path:path tip:tip useSSL:NO completionHandler:completionBlock errorHandler:errorBlock finishHandler:finishBlock];
    
}
- (NSURLSessionDataTask* )RunRequest:(NSMutableDictionary *)  dict
                                path:(NSString *)path
                                tip :(NSString*)tip
                              useSSL:(BOOL)useSSL
                   completionHandler:(ResponseBlock)completionBlock
                        errorHandler:(AFNErrorBlock)errorBlock
                       finishHandler:(FinishBlock)finishBlock{
    
    NSMutableDictionary *paramDict = [self obtainParametersDictionaryWithDic:dict];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //headers
    [manager.requestSerializer setValue:@"gzip, deflate, sdch" forHTTPHeaderField:@"Accept-Encoding"];
    [manager.requestSerializer setValue:@"zh,CN" forHTTPHeaderField:@"Accept-Language"];
    [manager.requestSerializer setValue:@"text/json" forHTTPHeaderField:@"Content-Type"];
    
    AFJSONResponseSerializer *serializer = [AFJSONResponseSerializer serializer];
    serializer.acceptableContentTypes = [NSSet setWithObjects:@"text/json",@"text/html",@"application/json", nil];
    manager.responseSerializer = serializer;
    
    NSURLSessionDataTask *task = nil;
    __weak typeof(self) weakSelf = self;
    task = [manager POST:path parameters:paramDict constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        //        if (paramDict) {
        //            NSError *error;
        //            NSData *jsonData = [NSJSONSerialization dataWithJSONObject:paramDict options:0 error:&error];
        //            NSAssert(jsonData, @"Failure building JSON: %@", error);
        //            NSLog(@"Json Data Image Upload %@",jsonData);
        //            NSAssert(jsonData, @"Failure building JSON: %@", error);
        //            NSDictionary *jsonHeaders = @{@"Content-Disposition" : @"form-data; name=\"parameters\"",
        //                                          @"Content-Type"        : @"application/json",
        //                                          @"Accept"              : @"application/json"};
        //            [formData appendPartWithHeaders:jsonHeaders body:jsonData];
        //
        //        }
        [weakSelf showHUDWithTip:tip];
        //        for (NSString *key in [weakSelf.postDict allKeys]){
        //            [formData appendPartWithFileData:[weakSelf.postDict valueForKeyPath:key] name:key fileName:@"content" mimeType:@"application/octet-stream"];
        //        }
        //        [weakSelf.postDict removeAllObjects];
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [weakSelf hideHUD];
        [weakSelf analysisDataWithObject:responseObject path:task.currentRequest.description completionHandler:completionBlock finishHandler:finishBlock];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [weakSelf hideHUD];
        if (error.code==NSURLErrorCancelled) {
            error = [[NSError alloc] initWithDomain:@"" code:999 userInfo:nil];
        }else{
            error = [[NSError alloc] initWithDomain:kProtocolLocalizedDescription code:201 userInfo:nil];
        }
        if (errorBlock) {
            errorBlock(error);
        }
    }];
    return task;
}




- (NSURLSessionDataTask*)RunRequest:(NSMutableDictionary *)dict
                               path:(NSString *)path
                  completionHandler:(ResponseBlock)completionBlock
                       errorHandler:(AFNErrorBlock)errorBlock
                      finishHandler:(FinishBlock)finishBlock{
    
    return [self RunRequest:dict path:path useSSL:NO completionHandler:completionBlock errorHandler:errorBlock finishHandler:finishBlock];
    
}

- (NSURLSessionDataTask* )RunRequest:(NSMutableDictionary *)  dict
                                path:(NSString *)path
                              useSSL:(BOOL)useSSL
                   completionHandler:(ResponseBlock)completionBlock
                        errorHandler:(AFNErrorBlock)errorBlock
                       finishHandler:(FinishBlock)finishBlock{
    
    NSMutableDictionary *paramDict = [self obtainParametersDictionaryWithDic:dict];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //headers
    [manager.requestSerializer setValue:@"gzip, deflate, sdch" forHTTPHeaderField:@"Accept-Encoding"];
    [manager.requestSerializer setValue:@"zh,CN" forHTTPHeaderField:@"Accept-Language"];
    [manager.requestSerializer setValue:@"text/json" forHTTPHeaderField:@"Content-Type"];
    
    AFJSONResponseSerializer *serializer = [AFJSONResponseSerializer serializer];
    serializer.acceptableContentTypes = [NSSet setWithObjects:@"text/json",@"text/html",@"application/json", nil];
    manager.responseSerializer = serializer;
    
    NSURLSessionDataTask *task = nil;
    __weak typeof(self) weakSelf = self;
    task = [manager POST:path parameters:paramDict constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
//        if (paramDict) {
//            NSError *error;
//            NSData *jsonData = [NSJSONSerialization dataWithJSONObject:paramDict options:0 error:&error];
//            NSAssert(jsonData, @"Failure building JSON: %@", error);
//            NSLog(@"Json Data Image Upload %@",jsonData);
//            NSAssert(jsonData, @"Failure building JSON: %@", error);
//            NSDictionary *jsonHeaders = @{@"Content-Disposition" : @"form-data; name=\"parameters\"",
//                                          @"Content-Type"        : @"application/json",
//                                          @"Accept"              : @"application/json"};
//            [formData appendPartWithHeaders:jsonHeaders body:jsonData];
//
//        }
        [weakSelf showHUD];
//        for (NSString *key in [weakSelf.postDict allKeys]){
//            [formData appendPartWithFileData:[weakSelf.postDict valueForKeyPath:key] name:key fileName:@"content" mimeType:@"application/octet-stream"];
//        }
//        [weakSelf.postDict removeAllObjects];
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [weakSelf hideHUD];
        [weakSelf analysisDataWithObject:responseObject path:task.currentRequest.description completionHandler:completionBlock finishHandler:finishBlock];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [weakSelf hideHUD];
        if (error.code==NSURLErrorCancelled) {
            error = [[NSError alloc] initWithDomain:@"" code:999 userInfo:nil];
        }else{
            error = [[NSError alloc] initWithDomain:kProtocolLocalizedDescription code:201 userInfo:nil];
        }
        if (errorBlock) {
            errorBlock(error);
        }
    }];
     return task;
}
#pragma mark - 处理公共参数
- (NSMutableDictionary *)obtainParametersDictionaryWithDic:(NSMutableDictionary *)dict{
    
    NSMutableDictionary *paramDict = [[NSMutableDictionary alloc] initWithDictionary:dict];
    
//    NSString *token = [UserConfig getUserToken];
//    if (token) {
//        [paramDict setObject:token forKey:@"token"];
//        [paramDict setObject:_S(@"%.0f",[UserConfig getUserInfo].uid) forKey:@"uid"];
//        //        [paramDict setObject:_S(@"%d",[UserConfig getUserInfo].type) forKey:@"type"];
//    }
    NSArray *keys = [dict allKeys];
    NSArray *sortedArray = [keys sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        return [obj1 compare:obj2];
    }];
    NSMutableString *paramStr = [[NSMutableString alloc] init];
    for (NSString *key in sortedArray) {
        NSString *encodeStr = _S(@"%@",[paramDict objectForKey:key]);
        if (encodeStr == nil || (NSNull *)(encodeStr) == [NSNull null]) {
            encodeStr = @"";
        }
        [paramStr appendString:[NSString stringWithFormat:@"%@%@",key,encodeStr]];
    }
    [paramStr appendFormat:@"%@", [NSString stringWithFormat:@"%@",@"45572acd28c778d992527c7efc3ae8c5"]];
    [paramDict setObject:[paramStr md5String] forKey:@"signed"];
//    NSLog(@"%@",paramStr);
//    NSLog(@"%@",[paramStr md5String]);
     //NSLog(@"-----%@",paramDict);
    
    return paramDict;
}

#pragma mark - 分析数据
- (void)analysisDataWithObject:(id)responseObject
                          path:(NSString *)path
             completionHandler:(ResponseBlock)completionBlock
                 finishHandler:(FinishBlock)finishBlock{
    
    id reDict = responseObject;
    //NSLog(@" ===>>>单点登录%@>",reDict);
    NSDictionary *head = reDict[@"head"];
    
    int statusCode = [[head objectForKey:@"statuscode"] intValue];
    if (statusCode == 700) {
        
        NSLog(@"单点登录：%d ",statusCode);
        //单点登录
//        [UserConfig setUserInfo:nil];
//        [UserConfig setUserToken:nil];
        
        WKLoginViewController *loginVc = [[WKLoginViewController alloc]init];
        NSString *account =  [[NSUserDefaults standardUserDefaults] objectForKey:@"account"];
        NSString *password = [[NSUserDefaults standardUserDefaults] objectForKey:@"psd"];
        loginVc.isReset = YES;
        loginVc.account = account;
        loginVc.psd = password;
        WKAlerView *alert =  [[WKAlerView alloc]initWithFrame:[UIScreen mainScreen].bounds
                                                      message:@"你的账号已在另一台手机登录" tip:nil title1:@"退出应用" title2:@"重新登录"];
        [[UIApplication sharedApplication].keyWindow addSubview:alert];

        alert.confirmBlock = ^{
            exit(0);
        };
        alert.cancelBlock = ^{
            //删除登录时的数据
            [WKLoginHandel removeLoginData];
            [WKUniversal removeImgData];
            //         [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"account"];
            //         [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"psd"];
            [[NSUserDefaults standardUserDefaults]setObject:@"" forKey:@"account"];
            [[NSUserDefaults standardUserDefaults]setObject:@"" forKey:@"psd"];
            [[NSUserDefaults standardUserDefaults]synchronize];
            [UIApplication sharedApplication].keyWindow.rootViewController =loginVc;
        };
    } else if (statusCode == 200 || reDict==nil){
        dispatch_async(dispatch_get_main_queue(), ^{
            if (completionBlock) {
                completionBlock(reDict);
            }
        });
        reDict = nil;
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        if (finishBlock) {
            finishBlock(reDict);
        }
    });
}

#pragma mark - 下载文件
- (void)DownloadFileFrom:(NSString *)remoteURL
                  toFile:(NSString *)filePath
       completionHandler:(DownloadBlock)completionBlock
            errorHandler:(AFNErrorBlock)errorBlock{
    
    __weak typeof(self) weakSelf =  self;
    
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:remoteURL]];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSURLSessionDownloadTask *downloadtask = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        if (weakSelf.delegate != nil && [weakSelf.delegate respondsToSelector:@selector(completePercentageWithFloat:)]) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.delegate completePercentageWithFloat:downloadProgress.fractionCompleted];
            });
        }
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        
        return [NSURL fileURLWithPath:filePath];
        
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        
        if (error) {
            if (errorBlock) {
                errorBlock(error);
            }
            
        }else{
            if (completionBlock) {
                completionBlock([filePath absoluteString]);
            }
        }
    }];
    
    [downloadtask resume];
    
}
#pragma mark - Data Upload
- (NSURLSessionDataTask *)uploadDataWithPath:(NSString *)path
                                  parameters:(NSMutableDictionary *)parameters
                                     manager:(AFHTTPSessionManager *)manager
                           completionHandler:(ResponseBlock)completionBlock
                                errorHandler:(AFNErrorBlock)  errorBlock
                               finishHandler:(FinishBlock)finishBlock
{
    
    __weak typeof(self) weakSelf = self;
    NSURLSessionDataTask *task = [manager POST:path parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [weakSelf showHUDWithTip:@"上传中..."];
        for (NSString *key in [weakSelf.postDict allKeys])
        {
            [formData appendPartWithFileData:[weakSelf.postDict valueForKeyPath:key] name:key fileName:@"imageData" mimeType:@"application/octet-stream"];
            
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        if (weakSelf.delegate != nil && [weakSelf.delegate respondsToSelector:@selector(completePercentageWithFloat:)]) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.delegate completePercentageWithFloat:uploadProgress.fractionCompleted];
            });
        }    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            [weakSelf hideHUD];
            [weakSelf analysisDataWithObject:responseObject path:task.currentRequest.description completionHandler:completionBlock finishHandler:finishBlock];
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [weakSelf hideHUD];
            if (error.code==NSURLErrorCancelled) {
                error = [[NSError alloc] initWithDomain:@"" code:999 userInfo:nil];
            }
            else{
                error = [[NSError alloc] initWithDomain:kProtocolLocalizedDescription code:201 userInfo:nil];
            }
            if (errorBlock) {
                errorBlock(error);
            }
        }];
    return task;
}

#pragma mark - 取消请求
- (void)cancelOperation:(NSURLSessionDataTask *)task {
    if (task) {
        [task cancel];
    }
}
- (void)showHUDWithTip:(NSString*)tip{
    
    [self.HUD showAnimated:YES];
    UIWindow *window =  [[[UIApplication sharedApplication] delegate] window];
    _HUD = [MBProgressHUD showHUDAddedTo:window animated:YES];
    _HUD.bezelView.style = MBProgressHUDBackgroundStyleSolidColor;
    _HUD.bezelView.color = [UIColor colorWithWhite:0 alpha:0.7];
    _HUD.mode = MBProgressHUDModeIndeterminate;
    _HUD.label.text = tip;
    _HUD.label.textColor = [UIColor whiteColor];
    _HUD.label.font = [UIFont systemFontOfSize:15];
    _HUD.activityIndicatorColor = [UIColor whiteColor];
//    [UIActivityIndicatorView appearanceWhenContainedIn:<#(nullable Class<UIAppearanceContainer>), ...#>, nil]
//    [UIActivityIndicatorView appearanceWhenContainedIn:[MBProgressHUD class], nil].color = [UIColor whiteColor];
    _HUD.animationType = MBProgressHUDAnimationFade;
    _HUD.minShowTime = 0;
}

- (void)showHUD{
    
    [self.HUD showAnimated:YES];
    UIWindow *window =  [[[UIApplication sharedApplication] delegate] window];
    _HUD = [MBProgressHUD showHUDAddedTo:window animated:YES];
    _HUD.bezelView.style = MBProgressHUDBackgroundStyleSolidColor;
    _HUD.bezelView.color = [UIColor colorWithWhite:0 alpha:0.7];
    _HUD.mode = MBProgressHUDModeIndeterminate;
    _HUD.label.text = @"加载中...";
    _HUD.label.textColor = [UIColor whiteColor];
    _HUD.label.font = [UIFont systemFontOfSize:15];
    _HUD.activityIndicatorColor = [UIColor whiteColor];
//    [UIActivityIndicatorView appearanceWhenContainedIn:[MBProgressHUD class], nil].color = [UIColor whiteColor];
    _HUD.animationType = MBProgressHUDAnimationFade;
    _HUD.minShowTime = 0;
}
- (void)hideHUD{
    
    [_HUD hideAnimated:YES];
    [_HUD removeFromSuperViewOnHide];
}
#pragma mark - lazy
- (NSMutableDictionary *)postDict{
    if (!_postDict) {
        _postDict = [[NSMutableDictionary alloc] init];
    }
    return _postDict;
}

- (NSMutableDictionary *)postFileDict{
    if (!_postFileDict) {
        _postFileDict = [[NSMutableDictionary alloc] init];
    }
    return _postFileDict;
}


@end
